package com.boss.salary.service.impl;

import com.boss.common.entity.PageDTO;
import com.boss.common.entity.WfActionDTO;
import com.boss.common.enums.ActionTypeEnum;
import com.boss.common.enums.StatusCodeEnum;
import com.boss.common.service.ICommonService;
import com.boss.common.util.DateUtils;
import com.boss.framework.dto.PaginationDTO;
import com.boss.framework.exception.AppRuntimeException;
import com.boss.salary.constant.SystemDictConstant;
import com.boss.salary.dao.*;
import com.boss.salary.entity.AgencyInfo;
import com.boss.salary.entity.AgencyVerify;
import com.boss.salary.entity.BaseData;
import com.boss.salary.entity.ConfigCtrl;
import com.boss.salary.service.IBaseDataService;
import com.boss.salary.service.IFinancialAuditService;
import com.boss.salary.vo.FinancialAuditVO;
import com.boss.salary.workflow.service.ISalaryWorkFlowService;
import com.boss.sys.ca.user.dto.UserDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FinancialAuditServiceImpl implements IFinancialAuditService {

    /**
     * 引入日志框架常量
     */
    private final static Logger logger = LoggerFactory.getLogger(FinancialAuditServiceImpl.class);

    @Autowired
    private IFinancialAuditDao iFinancialAuditDao;

    @Autowired
    private IAgencyVerifyDao iAgencyVerifyDao;
    @Autowired
    private IAgencyInfoDao agencyInfoDao;
    @Autowired
    private ISalaryWorkFlowService iSalaryWorkFlowService;
    @Autowired
    private IPersonExtSubmitDao personExtSubmitDao;
    @Autowired
    private ISalaryMonthEndSubmitDao salaryMonthEndSubmitDao;
    @Autowired
    private IPayMentLockDao iPayMentLockDao;
    @Autowired
    private ISalWorkflowBackDao workflowBackDao;
    @Autowired
    private ICommonService commonService;
    @Autowired
    private IBaseDataService baseDataService;

    @Override
    public PageDTO<Map<String,Object>> queryFinancialAuditPage(UserDTO userDto, PaginationDTO paginationDTO,
                                                             Map<String, Object> queryParam,
                                                             List<String> childrenId,String tokenid) throws AppRuntimeException {

        // 查询工作流待办数量

        List<String> bizKeys = new ArrayList<>();
       // List<HashMap<String, String>> bizKeys=new ArrayList<>();
//        String bizKeys="";
        WfActionDTO wfActionDTO = new WfActionDTO();
        // 菜单id
        wfActionDTO.setMenuguid(queryParam.get("menuid").toString());
        wfActionDTO.setBizKeyName("biz_key");
        wfActionDTO.setYear(userDto.getYear()+"");
        wfActionDTO.setProvince(userDto.getProvince());
        // 流程状态
        // 待办
        if ("1".equals(queryParam.get("flag"))) {
            logger.info("===查询待办Begin====");
            wfActionDTO.setStatus(StatusCodeEnum.TODO.getCode());

//            bizKeys =commonService.getWorkflowWheresql(tokenid,wfActionDTO,"av");
            bizKeys = iSalaryWorkFlowService.queryWorkflowInfo(userDto,wfActionDTO,tokenid);
            logger.info("====查询待办End === " + bizKeys);
        }
        // 已办
        else if ("2".equals(queryParam.get("flag"))) {
            logger.info("===查询已办Begin====");
            // 获取已办
            wfActionDTO.setStatus(StatusCodeEnum.FINISHED.getCode());
//            bizKeys =commonService.getWorkflowWheresql(tokenid,wfActionDTO,"av");
            bizKeys = iSalaryWorkFlowService.queryWorkflowInfo(userDto,wfActionDTO,tokenid);
            // 获取曾经办数据
            //wfActionDTO.setStatus(StatusCodeEnum.ONCE_FINISHED.getCode());
            //List<String> onceBizKeys = iSalaryWorkFlowService.queryWorkflowInfo(userDto,wfActionDTO);
//            if (StringUtils.isEmpty(bizKeys)) {
//                bizKeys = new ArrayList<>();
//            }
            /*if (!StringUtils.isEmpty(onceBizKeys) && onceBizKeys.size() > 0) {
                bizKeys.addAll(onceBizKeys);
            }*/
            logger.info("====查询已办End === " + bizKeys);
        }
        if ("-1".equals(queryParam.get("flag"))) {
            logger.info("===查询被退回Begin====");
            wfActionDTO.setStatus(StatusCodeEnum.BESENDBACK.getCode());
//            bizKeys =commonService.getWorkflowWheresql(tokenid,wfActionDTO,"av");
            bizKeys = iSalaryWorkFlowService.queryWorkflowInfo(userDto,wfActionDTO,tokenid);
            logger.info("====查询被退回End === " + bizKeys);
        }
        if("-2".equals(queryParam.get("flag"))){
            logger.info("===查询已退回Begin====");
            wfActionDTO.setStatus(StatusCodeEnum.BACK.getCode());
//            bizKeys =commonService.getWorkflowWheresql(tokenid,wfActionDTO,"av");
            bizKeys = iSalaryWorkFlowService.queryWorkflowInfo(userDto,wfActionDTO,tokenid);
            logger.info("====查询已退回End === " + bizKeys);
        }
        // 查询合计
//        logger.info("====查询审核数据START === " +  DateUtils.getCurrentTimeStamp());
//        //FinancialAuditVO financialAuditVO = iFinancialAuditDao.queryFinancialAuditDataTotal(queryParam, bizKeys, childrenId);
//        logger.info("====查询审核数据END === " + DateUtils.getCurrentTimeStamp());
        // 查询列表数据
        logger.info("====查询审核数据明细START === " +  DateUtils.getCurrentTimeStamp());
        List<BaseData> baseDatas = baseDataService.selectBaseDataList("autoShow", userDto.getProvince());
        List<Map<String,Object>> list = iFinancialAuditDao.queryFinancialAuditPage(paginationDTO, queryParam, bizKeys, childrenId,baseDatas);
        logger.info("====查询审核数据明细END === " +  DateUtils.getCurrentTimeStamp());

        int total = iFinancialAuditDao.queryFinancialAuditTotal(queryParam, bizKeys, childrenId);
        PageDTO<Map<String,Object>> pageDTO = new PageDTO<>();
        pageDTO.setRows(list);
        pageDTO.setTotal(total);
        return pageDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)//@GlobalTransactional(timeoutMills=300000)
    public void financialAuditPass(UserDTO userDto, FinancialAuditVO financialAuditVO, String tokenid) throws AppRuntimeException {
        List<AgencyVerify> agencyVerify1s = iAgencyVerifyDao.getAgencyVerifyByAgencyIds(financialAuditVO.getAgencyIds());
        List<AgencyInfo> agencyInfos=agencyInfoDao.queryAgencyInfo(financialAuditVO.getAgencyIds());
        Map<String,String> isPaymentAgency=new HashMap<>();
        for(AgencyInfo agencyInfo:agencyInfos){//将是否是需要生成支付单位的判断加到map中，后续方法取值判断用
            isPaymentAgency.put(agencyInfo.getId(),agencyInfo.getIsPaymentAgency());
        }
        if(!StringUtils.isEmpty(agencyVerify1s)) {
            WfActionDTO<List<AgencyVerify>> wfActionDTO = new WfActionDTO();
            wfActionDTO.setMenuguid(financialAuditVO.getMenuid());
            // 退回
            wfActionDTO.setActionType(ActionTypeEnum.WF_AUDIT.getActionTypeCode());
            wfActionDTO.setBizDatas(agencyVerify1s);
            wfActionDTO.setBizKeyName("bizKey");
            wfActionDTO.setMessage(financialAuditVO.getAuditExplain());

            // 财政审核通过后，执行工作流节点到下一节点
            for (AgencyVerify agencyVerify1 : agencyVerify1s) {
                // 修改单位表财政审核信息
                agencyVerify1.setUpdateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
                agencyVerify1.setSalaryInfoVerifiedCode(financialAuditVO.getMenuname() + "通过");
                if (!StringUtils.isEmpty(financialAuditVO.getParams()) &&
                        financialAuditVO.getParams().contains(SystemDictConstant.FINANCIAL_FLOW_REPORT)) {
                    //判断是否为终审节点
                    agencyVerify1.setIsConfirmSubmit(SystemDictConstant.IS_TRUE);
                    if("0".equals(isPaymentAgency.get(agencyVerify1.getAgencyId()))){//判断单位是否是实拨单位，实拨单位跳过生成支付直接生成银行数据
                        agencyVerify1.setIsPayDataCreated(SystemDictConstant.IS_TRUE);
                    }
                }
//            agencyVerify1.setAuditExplain(financialAuditVO.getMenuname() + "：" + financialAuditVO.getAuditExplain());
            }
            iAgencyVerifyDao.batchUpdateFinancialVerifyStatus(agencyVerify1s);

            logger.info("==== 工作流财政审核通过Start  ===");
            iSalaryWorkFlowService.doSalaryFlowList(userDto, wfActionDTO,tokenid);
            logger.info("==== 工作流财政审核通过完毕End  ===");
        }
    }

    /**
     * 审核岗退回
     * @param userDto
     * @param financialAuditVO
     * @throws AppRuntimeException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)//@GlobalTransactional(timeoutMills=300000)
    public void financialAuditReject(UserDTO userDto, FinancialAuditVO financialAuditVO, String tokenid) throws AppRuntimeException {

        List<AgencyVerify> agencyVerify1s = iAgencyVerifyDao.getAgencyVerifyByAgencyIds(financialAuditVO.getAgencyIds());
        String year=iAgencyVerifyDao.currentYear(financialAuditVO.getAgencyIds());
        if(!StringUtils.isEmpty(agencyVerify1s)) {
            WfActionDTO<List<AgencyVerify>> wfActionDTO = new WfActionDTO();
            wfActionDTO.setMenuguid(financialAuditVO.getMenuid());
            // 退回
            wfActionDTO.setActionType(ActionTypeEnum.WF_BACK.getActionTypeCode());
            wfActionDTO.setBizDatas(agencyVerify1s);
            wfActionDTO.setBizKeyName("bizKey");
            wfActionDTO.setMessage(financialAuditVO.getAuditExplain());
            List<String> agencyIds=financialAuditVO.getAgencyIds();
            List<String> backe2agencyIds=new ArrayList<>();//需要退回到单位的agencyId集合

            // 财政审核退回后，执行工作流节点到上一节点
            for (AgencyVerify agencyVerify1 : agencyVerify1s) {

                // 修改单位表财政审核信息
                agencyVerify1.setUpdateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
                agencyVerify1.setSalaryInfoVerifiedCode(financialAuditVO.getMenuname() + "退回");
                agencyVerify1.setAuditExplain(financialAuditVO.getMenuname() + "：" + financialAuditVO.getAuditExplain());
                agencyVerify1.setIsPayDataCreated(SystemDictConstant.IS_FALSE);
                //根据状态判断数据走向
                if (!StringUtils.isEmpty(financialAuditVO.getParams()) &&
                        financialAuditVO.getParams().contains(SystemDictConstant.WORK_FLOW_REPORT)) {
                    //存在退回到单位信息则
                    agencyVerify1.setIsSalarySubmit(Integer.parseInt(SystemDictConstant.IS_REJECT));
                    if (SystemDictConstant.IS_SUBMIT.equals(agencyVerify1.getIsAuto())||"220723990".equals(userDto.getProvince())||
                            financialAuditVO.getParams().contains(SystemDictConstant.WORK_FLOW_REPORT_START) ) {
                        agencyVerify1.setIsSubmitInAgency(Integer.parseInt(SystemDictConstant.IS_REJECT));
                    }
                    agencyVerify1.setIsAuto(String.valueOf(SystemDictConstant.IS_FALSE));//修改自动上报状态为非自动上报
                }
                agencyVerify1.setIsConfirmSubmit(SystemDictConstant.IS_FALSE);
                //iAgencyVerifyDao.updateFinancialVerifyStatus(agencyVerify1);
                // 调用工作流退回
            }
            if (!StringUtils.isEmpty(financialAuditVO.getParams()) &&
                    financialAuditVO.getParams().contains(SystemDictConstant.WORK_FLOW_REPORT)) {
                //查询退回节点，若存在则按设置的退回节点退回，不存在则按默认退回
                String backMenuId=workflowBackDao.getBackMenuId(userDto.getProvince(),financialAuditVO.getMenuid());
               if(!StringUtils.isEmpty(backMenuId)){
                   wfActionDTO.setActionType(ActionTypeEnum.WF_BACK_NODE.getActionTypeCode());
                   wfActionDTO.setBackMenuguid(backMenuId);
               }
                //若为带退回到单位标识则，删除上报数据
                personExtSubmitDao.batchPhysicalDeletePersonExtSubmit(userDto.getProvince(), agencyIds);
                salaryMonthEndSubmitDao.batchPhysicalDeleteSalaryMonthSubmit(userDto.getProvince(), agencyIds);
                //获取已锁定指标
                List<Map<String,Object>> payLockMap=iPayMentLockDao.selectPayMentLock(agencyIds);
                //解冻指标
                if(!CollectionUtils.isEmpty(payLockMap)) {
                    commonService.batchGocpurbudgetThaw(payLockMap, userDto.getProvince(), year, tokenid,userDto);
                    //清楚指标锁定表该单位的锁定信息
                    iPayMentLockDao.batchPhysicalDeletePayMentLock(agencyIds);
                }
            }
            iAgencyVerifyDao.batchUpdateFinancialVerifyStatus(agencyVerify1s);

            logger.info("==== 工作流财政审核退回Start  ===");
            iSalaryWorkFlowService.doSalaryFlowList(userDto, wfActionDTO,tokenid);
            logger.info("==== 工作流财政审核退回完毕End  ===");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)//@GlobalTransactional(timeoutMills=300000)
    public void financialAuditRevoke(UserDTO userDto, FinancialAuditVO financialAuditVO, String tokenid) throws AppRuntimeException {
        // 财政审核撤销审核
        List<AgencyVerify> agencyVerify1s = iAgencyVerifyDao.getAgencyVerifyByAgencyIds(financialAuditVO.getAgencyIds());
        for (AgencyVerify agencyVerify1 : agencyVerify1s) {
            // 获取单位审核状态信息

            // 修改单位表财政审核信息
            agencyVerify1.setUpdateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
            agencyVerify1.setSalaryInfoVerifiedCode(financialAuditVO.getMenuname() + "撤销审核");
            agencyVerify1.setIsConfirmSubmit(SystemDictConstant.IS_FALSE);
            agencyVerify1.setIsPayDataCreated(SystemDictConstant.IS_FALSE);
            // 调用工作流撤销审核


        }
        WfActionDTO<List<AgencyVerify>> wfActionDTO = new WfActionDTO();
        wfActionDTO.setMenuguid(financialAuditVO.getMenuid());
        // 撤销
        wfActionDTO.setActionType(ActionTypeEnum.WF_RECALL.getActionTypeCode());
        wfActionDTO.setBizDatas(agencyVerify1s);
        wfActionDTO.setBizKeyName("bizKey");
        wfActionDTO.setMessage(financialAuditVO.getAuditExplain());

        iAgencyVerifyDao.batchUpdateFinancialVerifyStatus(agencyVerify1s);

        logger.info("==== 工作流财政审核退回START  ===");
        iSalaryWorkFlowService.doSalaryFlowList(userDto, wfActionDTO,tokenid);
        logger.info("==== 工作流财政审核退回完毕End  ===");
    }

    @Override
    public Map<String, Object> getPayMoneyControlWarningMessage(UserDTO userDTO, String agencyId) {
        ConfigCtrl cc=commonService.selectConfigCtrlByTypeMof("payMoneyControl",userDTO.getProvince());
        Map<String, Object> request=new HashMap<>();
        if(cc==null){
            request.put("configCtrl","0");
            return request;
        }
        StringBuffer sb=new StringBuffer();
        List<Map<String,Object>> warningPersons=iFinancialAuditDao.getPayMoneyControlWarningMessage(agencyId,cc.getCtrlNum());
        if(CollectionUtils.isEmpty(warningPersons)){
            request.put("configCtrl","0");
            return request;
        }
        for(Map<String,Object> person:warningPersons){
            sb.append(person.get("person_name")).append("实发工资大于").append(cc.getCtrlNum()).append("</br>");
        }
        request.put("configCtrl","1");
        request.put("message",sb.toString());
        return request;
    }
}
